import { login, logout, getInfo } from "@/api/user";
import { getToken, setToken, removeToken } from "@/utils/auth";

const user = {
  state: {
    token: getToken(),
    name: "",
    avatar: "",
    roles: [],
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
    SET_NAME: (state, name) => {
      state.name = name;
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar;
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles;
    },
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim();
      const password = userInfo.password;
      const code = userInfo.code;
      const uuid = userInfo.uuid;
      return new Promise((resolve, reject) => {
        login(username, password, code, uuid)
          .then((res) => {
            setToken(res.token);
            commit("SET_TOKEN", res.token);
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo()
          .then((res) => {
            const user = res.user;

            if (!user) {
              reject("获取用户信息失败，请重新登录");
              return;
            }

            // 解析角色和权限信息
            const roles = res.roles || [];
            const permissions = res.permissions || [];

            // 设置用户信息
            commit("SET_NAME", user.nickName || user.userName);

            // 保存用户ID到localStorage，以便在评论等功能中使用
            if (user.userId) {
              localStorage.setItem("userId", user.userId);
            }

            // 处理头像路径，确保是完整的URL
            let avatar = "";
            if (user.avatar) {
              // 如果是完整URL则直接使用，否则拼接服务器地址
              if (user.avatar.startsWith("http")) {
                avatar = user.avatar;
              } else {
                avatar = process.env.VUE_APP_BASE_API
                  ? process.env.VUE_APP_BASE_API + user.avatar
                  : "/pet-api" + user.avatar;
              }
            }
            commit("SET_AVATAR", avatar);

            // 设置角色信息
            commit("SET_ROLES", roles);

            resolve(res);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 退出系统
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout()
          .then(() => {
            commit("SET_TOKEN", "");
            commit("SET_ROLES", []);
            removeToken();
            // 清除localStorage中的userId
            localStorage.removeItem("userId");
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
  },
};

export default user;
